#include "cpuranklistwidgetmainwindow.h"
#include "ui_cpuranklistwidgetmainwindow.h"

#include <httpclient.h>

#include <src/ui/widgets/cpurankitem.h>

CpuRankListWidgetMainWindow::CpuRankListWidgetMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::CpuRankListWidgetMainWindow)
{
    ui->setupUi(this);

    Response resp = HttpClient::instance().get("https://cpu.bmcx.com/web_system/bmcx_com_www/system/file/cpu/get_data/?lx=cpu&s=1&e=999999");
    if (resp.ok()) {

        for (const auto &var : resp.toList()) {
            auto item = new QListWidgetItem;
            auto widget = CpuRankItem::fromMap(var.toMap());

            item->setSizeHint(widget->sizeHint());
            ui->cpu_rank_list->addItem(item);
            ui->cpu_rank_list->setItemWidget(item, widget);
        }

        // 请求完成后回到主线程更新UI
        // QMetaObject::invokeMethod(cpu_rank_model, "layoutChanged", Qt::QueuedConnection);
    }

    connect(ui->cpu_filter, &QLineEdit::textChanged, this, [=](const QString &text){
        int count = ui->cpu_rank_list->count();
        for (int i = 0; i < count; ++i) {
            auto item = ui->cpu_rank_list->item(i);
            auto widget = qobject_cast<CpuRankItem*>(ui->cpu_rank_list->itemWidget(item));

            if (text.isEmpty()) {
                item->setHidden(false);
                continue;
            }

            item->setHidden(!widget->mingCheng().contains(text,Qt::CaseInsensitive));
        }
    });

    ui->cpu_rank_list->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection);
}

CpuRankListWidgetMainWindow::~CpuRankListWidgetMainWindow()
{
    delete ui;
}
